//
//  DataBaseSimple.m
//  侧滑Demo
//
//  Created by 毛志 on 14-7-2.
//  Copyright (c) 2014年 maozhi. All rights reserved.
//

#import "DataBaseOrder.h"
#import "FMDatabase.h"

@implementation DataBaseOrder
{
    FMDatabase * _dataBase;
}

static DataBaseOrder* _instance = nil;


-(id) initWithDB:(NSString *)fileName {
    self = [super init];
    if (self) {
        NSString * OrderPath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
        DLog(@"FMDB Path :%@",OrderPath);
        _dataBase = [FMDatabase databaseWithPath:OrderPath];
        if (![_dataBase open]) {
            return nil;
        }
        
        [self createTable];
    }
    return self;
}

-(void) close {
    [_dataBase close];
}

-(void)createTable{
    if (![_dataBase executeUpdate:@"create table if not exists ViewOrder (id integer primary key autoincrement, OrderData blob,OrderID integer,Status text,CreateTime text,UpdateTime text,unique(OrderID) on conflict replace)"]) {
        return;
    }
}

-(void)dropTable{
    [_dataBase executeUpdate:@"drop table if exists ViewOrder"];
}


- (void)insertDBwithViewOrderModelArray:(NSArray *)array useTransaction:(BOOL)useTransaction
{
    [_dataBase open];
    if (useTransaction) {
        [_dataBase beginTransaction];
        BOOL isRollBack = NO;
        @try {
            
                for (int i = 0; i<array.count; i++) {
                    ViewOrderModel *model = (ViewOrderModel *)array[i] ;

                    NSArray * params = [NSArray arrayWithObjects:model.order.data,[[NSNumber alloc] initWithLong:model.order.id],model.statusStr,model.createTimeStamp ,model.updateTimeStamp,nil];
                    if (![_dataBase executeUpdate:@"insert into ViewOrder (OrderData,OrderID,Status,CreateTime,UpdateTime) values (?,?,?,?,?)" withArgumentsInArray:params]) {
                        DLog(@"insertDBwithModelError");
                        return;
                    }

                }
        }
        @catch (NSException *exception) {
            isRollBack = YES;
            [_dataBase rollback];
        }
        @finally {
            if (!isRollBack) {
                [_dataBase commit];
            }
        }
        
    }
    else
    {

            
        for (int i = 0; i<array.count; i++) {
            ViewOrderModel *model = (ViewOrderModel *)array[i] ;
            
            NSArray * params = [NSArray arrayWithObjects:model.order.data,[[NSNumber alloc] initWithLong:model.order.id],model.statusStr,model.createTimeStamp ,model.updateTimeStamp,nil];
            if (![_dataBase executeUpdate:@"insert into ViewOrder (OrderData,OrderID,Status,CreateTime,UpdateTime) values (?,?,?,?,?)" withArgumentsInArray:params]) {
                DLog(@"insertDBwithModelError");
                return;
            }
            
        }

    }

}


- (void)deleteDBwithStatus:(NSString *)statusStr;
{
    if (![_dataBase executeUpdate:@"delete from ViewOrder where Status=?",statusStr]) {
        DLog(@"deleteDBwithModelError");
        return;
    }
}


- (void)deleteAll
{
    if (![_dataBase executeUpdate:@"delete from ViewOrder"]) {
        DLog(@"deleteAllwithModelError");
        return;
    }
}

- (void)deleteWithId:(int)orderId {
    if (![_dataBase executeUpdate:@"delete from ViewOrder where OrderID = %d",orderId]) {
        DLog(@"deleteAllwithModelError");
        return;
    }
}

- (void)updateDBwithKey:(UInt64)orderID withModel:(ViewOrderModel *)model
{
    if (![_dataBase executeUpdate:@"update ViewOrder set OrderData=?,CreateTime=?,UpdateTime=?,Status=? where OrderID = ?",model.order.data,model.createTimeStamp,model.updateTimeStamp,model.statusStr,[[NSNumber alloc] initWithLong:orderID]]) {

        return;
    }
}

- (NSArray *)selectDBwithStatus:(NSString *)statusStr;
{
    
    NSMutableArray *array = [[NSMutableArray alloc]init];
    
    FMResultSet * set = [_dataBase executeQuery:@"select * from ViewOrder where Status=? Order By UpdateTime desc",statusStr];
        while ([set next]) {
            
            ViewOrderModel *model = [[ViewOrderModel alloc]init];
            model.order =[ViewOrder parseFromData:[set dataForColumn:@"OrderData"]] ;
            model.statusStr = [set stringForColumn:@"Status"];
            model.createTimeStamp =[set stringForColumn:@"CreateTime"];
            model.updateTimeStamp = [set stringForColumn:@"UpdateTime"];
            [array addObject:model];
            
        }
        
    
    return array;
}

- (NSArray *)selectAll
{
    NSMutableArray *array = [[NSMutableArray alloc]init];
    FMResultSet * set = [_dataBase executeQuery:@"select * from ViewOrder Order By CreateTime desc,OrderID desc"];
    while ([set next]) {
        ViewOrderModel *model = [ViewOrderModel fromOrderVew:[ViewOrder parseFromData:[set dataForColumn:@"OrderData"]]];
        [array addObject:model];
        
    }
    return array;
}

@end
